package cn.com.dragonpass.psystem.common.util;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.metadata.TableStyle;
import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.handler.RowWriteHandler;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.alibaba.excel.write.style.column.AbstractColumnWidthStyleStrategy;
import com.alibaba.excel.write.style.column.SimpleColumnWidthStyleStrategy;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.jetbrains.annotations.NotNull;

import java.util.*;

import static org.apache.poi.ss.usermodel.BorderStyle.DOTTED;
import static org.apache.poi.ss.usermodel.BorderStyle.THICK;

public class Test2 {

    @NotNull
    public static WriteCellStyle getWriteCellStyle() {
        WriteCellStyle contentWriteCellStyle = new WriteCellStyle();

        contentWriteCellStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex());
        //设置 自动换行
        contentWriteCellStyle.setWrapped(true);
        //设置水平居中
        contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
        //设置垂直居中
        contentWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        contentWriteCellStyle.setBorderLeft(THICK);
        contentWriteCellStyle.setBorderTop(THICK);
        contentWriteCellStyle.setBorderRight(THICK);
        contentWriteCellStyle.setBorderBottom(THICK);
        contentWriteCellStyle.setBottomBorderColor(IndexedColors.BLACK.getIndex());
        contentWriteCellStyle.setRightBorderColor(IndexedColors.BLACK.getIndex());
        return contentWriteCellStyle;
    }

    @NotNull
    public static HorizontalCellStyleStrategy getHorizontalCellStyleStrategy() {
        // 头的策略
        WriteCellStyle headWriteCellStyle = new WriteCellStyle();
        headWriteCellStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex());
        WriteFont headWriteFont = new WriteFont();
        headWriteFont.setFontHeightInPoints((short) 10);
        headWriteCellStyle.setWriteFont(headWriteFont);
//        headWriteCellStyle.setWrapped(true);
        headWriteCellStyle.setBorderBottom(BorderStyle.THICK);
        headWriteCellStyle.setBorderLeft(BorderStyle.THIN);
        headWriteCellStyle.setLeftBorderColor(IndexedColors.BLACK.getIndex());
        headWriteCellStyle.setBottomBorderColor(IndexedColors.BLACK.getIndex());

        //内容策略
        WriteCellStyle contentWriteCellStyle = getWriteCellStyle();
        // 这个策略是 头是头的样式 内容是内容的样式 其他的策略可以自己实现
        return new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);
    }


    public static void main(String[] args) {
        String fileName = "D:\\example3.xlsx";

        HorizontalCellStyleStrategy horizontalCellStyleStrategy = getHorizontalCellStyleStrategy();
        ExcelWriter excelWriter = EasyExcel.write(fileName).build();
        List<WriteCellStyle> contentWriteCellStyleList=new ArrayList<>();
        contentWriteCellStyleList.add(new WriteCellStyle());
        WriteSheet writeSheet = EasyExcel.writerSheet(0, "sheetNamewwww").registerWriteHandler(new DefineStray(new WriteCellStyle(),contentWriteCellStyleList)).build();

        excelWriter.write(getHead(), writeSheet);
        excelWriter.write(getData(), writeSheet);

        excelWriter.finish();


//https://blog.csdn.net/qq_46548855/article/details/135817806
    }

    private static void excle2(String fileName) {
        List<List<String>> data = getData();
      //  HorizontalCellStyleStrategy specialHorizontalCellStyleStrategy = getSpecialHorizontalCellStyleStrategy();

        ExcelWriter excelWriter = EasyExcel.write(fileName)
                //.registerWriteHandler(new CustomRowWriteHandler(0,0,0,2))
               // . registerWriteHandler(new SimpleColumnWidthStyleStrategy(50))
              //  .registerWriteHandler(specialHorizontalCellStyleStrategy)
                .build();

        // 写入Excel
        WriteSheet sheet = EasyExcel.write(fileName)
                .sheet("Sheet1").build();


        //   excelWriter.write(getHead(),sheet);
        sheet.setHead(getHead());

        excelWriter.write(data,sheet);
        excelWriter.finish();
    }

    private static List<List<String>> getData() {
        List<List<String>> data = new ArrayList<>();
        data.add(Arrays.asList("币种编码" ,"币种名称 ","汇率 "));
        data.add(Arrays.asList("xxssss，。","yyyyyyysss","xxsssss "));
        return data;
    }

    private static List<List<String>> getHead() {
        List<List<String>> headList =new ArrayList<>();
        List<String> head=new ArrayList<>();



        String msg="1、导入字段说明\n" +
                "（1）币种编码：必填，需大写，如CNY、USD；\n" +
                "（2）币种名称：如人民币、美元等；\n" +
                "（3）汇率：必填，支持小数点后四位，不足四位补0，多余四位采用四舍五入；\n" +
                "2、若对应币种汇率无需更新，模板需要删除该币种数据；\n" +
                "3、以人民币为本位币导入汇率数据；";

        head.add(msg);
        headList.add(head);


        return headList;


    }



    public static class CustomRowWriteHandler implements RowWriteHandler {



        private int firstRow;
        private int lastRow;
        private int firstCol;
        private int lastCol;


        public CustomRowWriteHandler(int firstRow, int lastRow, int firstCol, int lastCol) {
            this.firstRow = firstRow;
            this.lastRow = lastRow;
            this.firstCol = firstCol;
            this.lastCol = lastCol;
        }

        @Override
        public void beforeRowCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Integer integer, Integer integer1, Boolean aBoolean) {
            //   System.out.println("..............");
        }

        @Override
        public void afterRowCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Row row, Integer integer, Boolean aBoolean) {
            // System.out.println("..............*********");
        }

        @Override
        public void afterRowDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Row row,
                                    Integer relativeRowIndex, Boolean isHead) {

            //  System.out.println(relativeRowIndex+"------->"+row.getRowNum());
            // 在这里编写你的自定义逻辑
            // 例如，给每一行添加一个公共的背景颜色
            // row.getCell(0).getCellStyle().setFillForegroundColor(IndexedColors.YELLOW.getIndex());
            // row.getCell(0).getCellStyle().setFillPattern(FillPatternType.SOLID_FOREGROUND);


            if ( relativeRowIndex.equals(firstRow)&&row.getRowNum()==0) {
                CellRangeAddress cellRangeAddress = new CellRangeAddress(firstRow, lastRow, firstCol, lastCol);
                writeSheetHolder.getSheet().addMergedRegion(cellRangeAddress);



            }
            if (relativeRowIndex == 0 &&row.getRowNum()==0) {
                row.setHeight((short) 2500);




            }else{
                Cell cell = row.getCell(0);
                CellStyle cellStyle = cell.getCellStyle();
                cellStyle.setWrapText(true);
                cellStyle.setBorderRight(BorderStyle.THIN);
                cellStyle.setRightBorderColor(IndexedColors.BLACK.getIndex());
                cell.setCellStyle(cellStyle);
            }
        }
    }


public     static  class DefineStray extends HorizontalCellStyleStrategy{


        private WriteCellStyle headWriteCellStyle;

        List<WriteCellStyle> contentWriteCellStyleList;
        public DefineStray(WriteCellStyle headWriteCellStyle,List<WriteCellStyle> contentWriteCellStyleList){
            super(headWriteCellStyle,contentWriteCellStyleList);

        }

    @Override
    protected void initCellStyle(Workbook workbook) {



        // 只针对第一列应用样式


        CellStyle style = workbook.getSheetAt(0).getWorkbook().getCellStyleAt(0);

        // 设置背景色
        style.setFillForegroundColor(IndexedColors.YELLOW.getIndex());
        style.setFillPattern(FillPatternType.SOLID_FOREGROUND);

        // 设置字体cell
        System.out.println("----------");

        Font font = workbook.createFont();
        font.setColor(IndexedColors.BLUE.getIndex()); // 设置字体颜色
        style.setFont(font);
        super.initCellStyle(workbook);
    }


    @Override
    protected void setContentCellStyle(Cell cell, Head head, Integer relativeRowIndex) {

        CellStyle style = cell.getCellStyle();

        // 设置背景色
        style.setFillForegroundColor(IndexedColors.YELLOW.getIndex());
        style.setFillPattern(FillPatternType.SOLID_FOREGROUND);

        // 设置字体cell
        System.out.println("----------");

        Font font = cell.getSheet().getWorkbook().createFont();
        font.setColor(IndexedColors.BLUE.getIndex()); // 设置字体颜色
        style.setFont(font);
        super.setContentCellStyle(cell, head, relativeRowIndex);
    }
}

}
